﻿
using System;
using UnityEngine;
//通用的NPC状态机
public class NpcAI
{
    private const string IDIE_NAME = "Idle";
    private const string ATTACK_NAME = "Attack";
    private Creature _owner;
    private StateMachine _machine;
    private StateIdle _stateIdle;
    private StateAttack _stateAttack;//自动追击
    public void Init(Creature owner)
    {
        _owner = owner;
        _machine = new StateMachine();
        _stateIdle = new StateIdle();

        _stateIdle.Init(_owner, _machine);
        _stateAttack = new StateAttack();
        _stateAttack.Init(_owner, _machine);

        _machine.RegisterState(IDIE_NAME, _stateIdle);
        _machine.RegisterState(ATTACK_NAME, _stateAttack);
        _machine.SetDefaultState(IDIE_NAME);
    }
    public void Loop()
    {
        
        sceneSystem();
        _machine.DoWork();
    }

    private void sceneSystem()
    {
        if (_owner.CurTarget != null)
        {
            var dis = Util.Distance2_5D(_owner.CurTarget.Position, _owner.Position);
            if (dis > GameSetting.MaxVisualSenseDis * 1.2)
            {
                _owner.CurTarget = null;
            }
            return; 
        }
        //选中最近的角色，攻击;
        float minDis = float.MaxValue;
        Role minDisRole = null;
        foreach (var rolePair in RoleMgr.GetInstance().AllRole)
        {

            var role = rolePair.Value;
            if (!role.CanBeAttack(_owner)) { continue; }

            var dis = Util.Distance2_5D(role.Position, _owner.Position);
            if (dis > GameSetting.MaxVisualSenseDis) { continue; }
            if (dis < minDis)
            {
                minDis = dis;
                minDisRole = role;
            }

        }
        _owner.CurTarget= minDisRole;
    }
    #region 状态定义
    private class StateIdle:State
    {
        //进入某个状态，需要做的准备或者初始化工作
        public override void EnterState() 
        {
            _owner.StopMove();
        }
        //在某个状态中 需要持续更新的逻辑
        public override void UpdateState() 
        {
            if (!_owner.IsAssistOrCastingSkill)
            {
                _machine.ChangeState(ATTACK_NAME);
            }
        }
        //退出某个状态，需要重置的一些数据
        public override void ExitState() { }
    }

    private class StateAttack:State
    {
        //进入某个状态，需要做的准备或者初始化工作
        public override void EnterState() 
        {
            _owner.CastSkill(3);
        }
        //在某个状态中 需要持续更新的逻辑
        public override void UpdateState() 
        {
            if (!_owner.IsAssistOrCastingSkill)
            {
                _machine.ChangeState(IDIE_NAME);
            }
        }
        //退出某个状态，需要重置的一些数据
        public override void ExitState() { }
    }
    #endregion 状态定义
}
